//收款页面
import React, {Component} from 'react';
import Platform from 'Platform';
import {
  StyleSheet,
  Text,
  View,
  Dimensions,
  Navigator,
  TouchableOpacity,
  TextInput,
  Modal,
  TouchableHighlight,
  Image,
  Alert,
} from 'react-native';
import Collection from '../components/Colloction';
import {connect} from 'react-redux';
import * as defaultStyles from '../constants/DefaultStyles';
import Icon from 'react-native-vector-icons/MaterialCommunityIcons';
import FIcon from 'react-native-vector-icons/FontAwesome';
import IconButton from '../components/IconButton';
import {Actions} from 'react-native-router-flux';
import Spinner from 'react-native-loading-spinner-overlay';
import { requestXML } from '../utils/RequestUtils';
import { json2xml_str } from '../utils/XmlUtils';
import JPushModule from 'jpush-react-native';


const data = [
    ['1'], ['2'], ['3'], ['DEL'],
    ['4'], ['5'], ['6'], ['C'],
    ['7'], ['8'], ['9'], ['+'],
    ['00'], ['0'], ['.'], ['='],
];

function removeThousand(str) {
  return str.replace(/,/g, '');
}

export class MainContainer extends Component {
  constructor(props) {
    super(props);
    this.state = {
      result: '0.00',
      modalVisible: false,
      //推送消息
    }
  }

  componentWillMount() {
    JPushModule.setAlias(merid,
      (success)=> {
        console.log("成功")
      }, (fail) => {
        console.log("失败")
      });

    storage.load({
      key: merid,
      autoSync: true,
      syncInBackground: true,
    }).then(ret => {
      console.log(ret);
      if (ret.messages === undefined) {
        return;
      }
      else {
        this.setState({messages: ret.messages})
      }
    }).catch(err => {
      console.warn(err.message);
      switch (err.name) {
        case 'NotFoundError':
          break;
        case 'ExpiredError':
          break;
      }
    });
  }

  _getResult(result) {
    this.setState({
      result: result,
    });
  }

  _getQRCode(type) {
    let tanstype = '80014'
    if (type === 'alipay') {
      tanstype = '80008';
    }
    this.setState({isLoading: true});
    console.log(this.state.code);
    let xml = json2xml_str(JSON.stringify({
      Request: {
        Head: {
          trace_no: '6',
          terminalno: '8',
          acceptidcode: merid,
          tanstype: tanstype,
          operateno: '3'
        },
        Body: {
          SIGN: '122',
          amt: String(parseFloat(removeThousand(this.state.result)) * 100)
        }}
    }));
    let respcd = '-1';
    const promise = requestXML('http://192.168.4.13:8084/icmp-ums/dhc/sys/mobile.do', xml, 20000);
    promise.then((object) => {
      console.log(object);
      let respcd = '-1';
      try {
        let Body = object.Response.Body;
        respcd = Body.respcd;
        if (respcd === '00') {
          this.setState({isLoading: false});
          if (type === 'wechat') {
            let QRValue = Body.code_url;
            Actions.createQRCode({
              title: '微信支付收款',
              amout: this.state.result,
              QRCodeValue: QRValue,
              paymentType: '2'
            });
          }
          else if (type === 'alipay') {
            let QRValue = Body.qr_code;
            Actions.createQRCode({
              title: '支付宝收款',
              amout: this.state.result,
              QRCodeValue: QRValue,
              paymentType: '1'
            });
          }
        }
        else {
          Alert.alert('提示', '获取二维码失败', [{text: '确定', onPress: () => {this.setState({isLoading: false})}}]);
          return;
        }
      }
      catch (err) {
        Alert.alert('提示', '返回数据格式出错', [{text: '确定', onPress: () => {this.setState({isLoading: false})}}]);
      }
    }, (reject) => {
      Alert.alert('提示', '请求出错，请检查网络连接', [{text: '确定', onPress: () => {this.setState({isLoading: false})}}]);
    });
  }

  _getPayment(type) {
    this.setState({
      modalVisible: false,
    });
    this._getQRCode(type);
    // if (type === 'wechat') {
    //
    //   let QRCodeValue = 'weixin' + removeThousand(this.state.result);
    //   Actions.createQRCode({
    //     title: '微信支付收款',
    //     amout: this.state.result,
    //     QRCodeValue: QRCodeValue,
    //     paymentType: '2'
    //   });
    // }
    // else if (type === 'alipay') {
    //   let QRCodeValue = 'alipay' + removeThousand(this.state.result);
    //   Actions.createQRCode({
    //     title: '支付宝收款',
    //     amout: this.state.result,
    //     QRCodeValue: QRCodeValue,
    //     paymentType: '1'
    //   });
    //
    // }
  }

  render() {
    return (
      <View style={styles.view}>
        {/*选择支付方式*/}
        <Spinner visible={this.state.isLoading}
                 textStyle={{color: 'white'}}  overlayColor={'rgba(0, 0, 0, 0.7)'}/>
        <Modal
          animationType={"fade"}
          transparent={true}
          visible={this.state.modalVisible}
          onRequestClose={() => console.log('支付窗口关闭')}
        >
          <View style={styles.modalContainer}>
            {/*中部白色框*/}
            <View style={styles.modalCenterContainer}>
              <View style={styles.modalCenterTop}>
                {/*关闭model按钮*/}
                <View style={styles.modalCloseBtn}>
                  <TouchableOpacity onPress={() => this.setState({modalVisible: false})}>
                    <FIcon name="times" size={20} color="black"/>
                  </TouchableOpacity>
                </View>

                {/*model标题*/}
                <View style={styles.modalTitle}>
                  <Text style={{fontSize: 17, marginLeft: -45}}>选择收款方式</Text>
                </View>
              </View>
              <View style={styles.modalCenterBottom}>
                <View style={styles.modalCenterBottomLeft}></View>
                {/*支付方式按钮*/}
                <View style={styles.modalCenterBottomRight}>
                  <IconButton text="支付宝支付" image={require('../imgs/alipay.png')} fontSize={17}
                            onPress={(type) => this._getPayment(type)} type="alipay"/>
                  <IconButton text="微信支付" image={require('../imgs/wechat.png')} fontSize={17}
                              onPress={this._getPayment.bind(this)} type="wechat"/>
                </View>
              </View>
            </View>
          </View>
        </Modal>

        <View style={styles.topView}>
          <View style={styles.topViewTop}>
            {/*<Text style={{flex: 1, marginLeft: 10, color: 'white'}}>v1.0.2</Text>*/}
            <TouchableOpacity style={{marginRight: 20, marginTop: 5}} onPress={() => Actions.messages()}>
              <Icon name={'bell-outline'} size={23} style={{color: 'white'}}/>
            </TouchableOpacity>
            <TouchableOpacity style={{marginRight: 5, marginTop: 5}}
                              onPress={() => {
                                  let amout = parseFloat(this.state.result);
                                  if (amout <= 0) {
                                    Alert.alert('提示','请输入收款金额');
                                  }
                                  else {
                                    let value = (parseFloat(removeThousand(this.state.result)) * 100).toString();
                                    Actions.scanPage({amout: this.state.result, value: value});
                                  }
                                  }}>
              <Icon name={'qrcode-scan'} size={23} style={{color: 'white'}}/>
            </TouchableOpacity>
          </View>

          <View style={styles.topViewMid}>
            <Text style={{color: 'white', fontSize: 18, fontWeight:'600'}}>收款金额</Text>
          </View>
          <View style={styles.topViewBottom}>
            <Text style={{fontSize: 50, color: 'white', textAlign: 'right', fontFamily: 'times'}} numberOfLines={1} minimumFontScale={1.0} adjustsFontSizeToFit={true}>{this.state.result}</Text>
          </View>
        </View>

        <View style={styles.bottomView}>
          <Collection data={data} style={styles.bottomViewTop}
                      getResult= {this._getResult.bind(this)}/>
          <View style={styles.bottomViewBottom}>
            <View style={{flex: 1, paddingLeft: 20, paddingRight: 10}}>
              <TouchableOpacity style={styles.bottomViewBtn}
                                onPress={() => {
                                  let amout = parseFloat(this.state.result);
                                  if (amout <= 0) {
                                    Alert.alert('提示','请输入收款金额');
                                  }
                                  else {
                                    let value = (parseFloat(removeThousand(this.state.result)) * 100).toString();
                                    Actions.scanPage({amout: this.state.result, value: value});
                                  }
                                  }}>
                <Text style={{textAlign: 'center',color: 'white',fontSize: 16}} >扫一扫收款</Text>
              </TouchableOpacity>
            </View>
            <View style={{flex: 1, paddingLeft: 10, paddingRight: 20}}>
              <TouchableOpacity style={styles.bottomViewBtn}
                                onPress={() => {
                                  let amout = parseFloat(this.state.result);
                                  if (amout <= 0) {
                                    Alert.alert('提示','请输入收款金额');
                                  }
                                  else {
                                    this.setState({modalVisible: true});
                                  }
                                  }}>
                <Text style={{textAlign: 'center',color: 'white',fontSize: 16}}>二维码收款</Text>
              </TouchableOpacity>
            </View>
          </View>
        </View>
      </View>
    );
  }
}

let deviceWidth = Dimensions.get('window').width;
const styles = StyleSheet.create({
  view: {
    flex: 1,
  },
  topView: {
    flex: 1,
    backgroundColor: defaultStyles.LIGHTBLUE,
  },
  topViewTop: {
    flex: 1,
    flexDirection: 'row',
    justifyContent: 'flex-end',
    paddingTop: defaultStyles.isIOS ? 30 : 10,
    paddingRight: 10,
  },
  topViewMid: {
    flex: 1,
    justifyContent: 'center',
    paddingLeft: 15,
  },
  topViewBottom: {
    flex: 2,
    paddingTop: defaultStyles.OS === 'ios' ? 30 : 10,
    paddingLeft: 15,
    paddingRight: 10,
  },
  bottomView: {
    flex: 2,
    backgroundColor: defaultStyles.WHITEOFBACKGROUND,
  },
  bottomViewTop: {
    flex: 5,
  },
  bottomViewBottom: {
    flex: 1,
    flexDirection: 'row',
  },
  bottomViewBtn: {
    marginTop: -30,
    height: 40,
    backgroundColor: defaultStyles.LIGHTBLUE,
    alignItems: 'center',
    justifyContent: 'center',
  },
  modalContainer: {
    flex: 1,
    justifyContent: 'center',
    alignItems: 'center',
    backgroundColor: 'rgba(0, 0, 0, 0.3)',
  },
  modalCenterContainer: {
    width: (defaultStyles.SCREENWIDTH - 60),
    height: 150,
    backgroundColor: 'white',
    borderRadius: 15,
  },
  modalCenterTop: {
    flex: 1,
    borderRadius:15,
    flexDirection: 'row',
  },
  modalCloseBtn: {
    flex: 1,
    paddingLeft: 15,
    paddingTop: 5,
    borderBottomWidth: 0.5,
    borderBottomColor: 'rgba(178, 180, 180, 1.00)',
  },
  modalTitle: {
    flex: 8,
    alignItems: 'center',
    justifyContent: 'center',
    borderBottomWidth: 0.5,
    borderBottomColor: 'rgba(178, 180, 180, 1.00)',
  },
  modalCenterBottom: {
    flex: 2,
    flexDirection: 'row',
  },
  modalCenterBottomLeft: {
    flex: 1,
  },
  modalCenterBottomRight: {
    flex: 15,
  },
  // modalPaymentBtn: {
  //   flex: 1,
  //   borderBottomWidth: 0.5,
  //   borderBottomColor: 'rgba(178, 180, 180, 1.00)',
  // },
  // modalPaymentBtnIcon: {
  //   flex: 1,
  //   justifyContent: 'center',
  //   alignItems: 'center',
  // },
  // modalPaymentBtnText: {
  //   flex: 4,
  //   paddingLeft: 15,
  // },
  // modalPaymentBtnArrow: {
  //   flex: 1,
  // },
});


export default connect()(MainContainer);